package cn.edu.nju.software.zp13.assignment6.servlet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import cn.edu.nju.software.zp13.assignment5.service.soapMessage.SOAPMsgProducer;
import cn.edu.nju.software.zp13.assignment5.service.soapMessage.SOAPMsgProducerImpl;
import cn.edu.nju.software.zp13.assignment6.util.InputStreamToStr;
import cn.edu.nju.software.zp13.client.assignment4.xslt.Transformer;

/**
 * Servlet implementation class Test
 */
@WebServlet("/Test")
public class Test extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Test() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		SOAPMsgProducer producer=new SOAPMsgProducerImpl(request.getInputStream());
		SOAPMessage receivedMsg=producer.produceSOAPMessage();
		try {
			SOAPBody body=receivedMsg.getSOAPPart().getEnvelope().getBody();
			Document doc=body.extractContentAsDocument();
			javax.xml.transform.Transformer transformer=Transformer.wellFormatUtf8Transformer();
			try {
				ByteArrayOutputStream out=new ByteArrayOutputStream();
				transformer.transform(new DOMSource(doc), new StreamResult(out));
				ByteArrayInputStream in=new ByteArrayInputStream(out.toByteArray());
				System.out.println(InputStreamToStr.run(in, "utf-8"));
			} catch (TransformerException e) {
				e.printStackTrace();
			}
			//System.out.println(body);
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		
		
		//SOAPMsgWriter.writeMsg(receivedMsg, System.out);
		doGet(request, response);
	}

}
